package org.darkforest.ucenter.service.impl;

import org.apache.commons.beanutils.BeanUtils;
import org.darkforest.common.util.DateUtil;
import org.darkforest.dao.mapper.*;
import org.darkforest.model.*;
import org.darkforest.ucenter.service.MessageService;
import org.darkforest.vo.StoreSellerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * 
 * 项目名称         :bwmall-ucenter
 * 文件名           :MessageServiceImpl.java
 * 开发公司及作者    :陈超
 * 版本号及开发日期  :Rev. 1.00 (2015年2月23日)
 */
@Service
public class MessageServiceImpl implements MessageService {
	
	@Autowired
	private MessageMapper messageMapper;
	@Autowired
	private MemberMsgSettingMapper memberMsgSettingMapper;

	@Autowired
	private MemberMapper memberMapper;

	@Autowired
	private StoreMsgMapper storeMsgMapper;

	@Autowired
	private MemberMsgTplMapper memberMsgTplMapper;

	@Override
	public void getMessageByMember(MessageSerachBean page) {
		page.setResultList(messageMapper.selectByMember(page));
		int notReadCount = 0;
		for(MessageVo vo : page.getResultList()){
			if(vo.getReadMemberId() == null || vo.getReadMemberId().trim().equals("")){
				notReadCount++;
			}
		}
		page.setNotReadCount(notReadCount);
	}

	@Override
	public MessageVo getMessageDetail(Integer messageId, Integer memberId, Integer notReadCount) {
		Map<String, Object> p = new HashMap<String, Object>();
		p.put("messageId", messageId);
		p.put("memberId", memberId);
		MessageVo vo = messageMapper.selectByDetailMember(p);
		if(vo != null && vo.getReadMemberId() != null && !vo.getReadMemberId().contains(memberId+"")){
			Message mes = new Message();
			mes.setMessageId(vo.getMessageId());
			mes.setMessageUpdateTime(DateUtil.unixTimeStampInt().intValue());
			String temp = vo.getReadMemberId();
			if(temp != null && !temp.trim().equals("")){
				temp += "," + memberId;
			}else{
				temp = "" + memberId;
			}
			mes.setReadMemberId(temp);
			messageMapper.updateByPrimaryKeySelective(mes);
			vo.setNotReadCount(notReadCount-1);
			vo.setMessageUpdateTime(mes.getMessageUpdateTime());
			vo.setReadMemberId(temp);
		}
		return vo;
	}

	@Override
	public void delMessageById(Integer[] messageId, Integer memberId) {
//		Map<String, Object> p = new HashMap<String, Object>();
//		p.put("messageId", messageId);
//		p.put("memberId", memberId);
//		messageMapper.deleteByMemberAndId(p);
		for(Integer i:messageId){
			messageMapper.deleteByPrimaryKey(i);

		}

	}

	@Override
	public MessageSettingVo getMemberMesSetting(Integer memberId) {
		MessageSettingVo vo = new MessageSettingVo();
		List<MemberMsgSetting> list = memberMsgSettingMapper.selectByMember(memberId);
		if(list.size() == 0){
			vo.allTrue();
			vo.setMemberId(memberId);
			list = createSettingList(vo);
			memberMsgSettingMapper.insertBatch(list);
		}
		for(MemberMsgSetting sett : list){
			try {
				BeanUtils.setProperty(vo, sett.getMmtCode(), sett.getIsReceive());
			} catch (IllegalAccessException e) {
				
			} catch (InvocationTargetException e) {
				
			}
			
		}
		return vo;
	}
	
	private List<MemberMsgSetting> createSettingList(MessageSettingVo vo){
		List<MemberMsgSetting> setList = new ArrayList<MemberMsgSetting>();
		String[] keyList = new String[] { "mmt_code", "arrival_notice",
				"consult_goods_reply", "consult_mall_reply",
				"order_deliver_success", "order_payment_success",
				"predeposit_change", "recharge_card_balance_change",
				"refund_return_notice", "voucher_use", "voucher_will_expire",
				"vr_code_will_expire" };
		for(String key : keyList){
			boolean isRec = true;
			try {
				isRec = Boolean.parseBoolean(BeanUtils.getProperty(vo, key));
			} catch (IllegalAccessException e) {
				
			} catch (InvocationTargetException e) {
				
			} catch (NoSuchMethodException e) {
				
			}
			MemberMsgSetting s = new MemberMsgSetting();
			s.setIsReceive(isRec);
			s.setMemberId(vo.getMemberId());
			s.setMmtCode(key);
			setList.add(s);
		}
		return setList;
	}

	@Override
	public void updateMemberMesSetting(MessageSettingVo vo) {
		List<MemberMsgSetting> list = createSettingList(vo);
		for(MemberMsgSetting s : list){
			memberMsgSettingMapper.updateByPrimaryKeySelective(s);
		}
	}

	@Override
	public Integer getNotReadCount(Integer memberId, List<Integer> stateList) {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("memberId",memberId);
		map.put("stateList",stateList);
		return messageMapper.selectNotReadCountByMember(map);
	}

	@Override
	public int insertMessage(Message record) {
		return messageMapper.insert(record);
	}

	@Override
	public void updateMessage(Message record) {
		messageMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public void sendSystemMessage(String messageBody, StoreSellerVo sellerVo, String mmtCode, String messageTitle) {

		List<Member> members = memberMapper.getMemberByCond(new Member(false));
		List<Message> messages = new ArrayList<Message>();

		StoreMsg storeMsg = new StoreMsg();
		storeMsg.setStoreId(sellerVo.getStoreId());
		storeMsg.setSmAddtime(DateUtil.unixTimeStampInt().intValue());
		storeMsg.setSmContent(messageBody);
		storeMsg.setSmReadids("0");
		storeMsg.setSmtCode(mmtCode);

		storeMsgMapper.insertSelective(storeMsg);



		if(!"0".equals(mmtCode)){
			//站内信

			MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey(mmtCode);
			String model = memberMsgTpl.getMmtMessageContent();

			for(Member member:members){

				model = model.replace("{1}",member.getMemberName()+"/"+member.getMemberWxNickName());
				model = model.replace("{2}",messageBody);
				model = model.replace("{3}",DateUtil.dateToString(new Date(),"yyyy-MM-dd"));
				Message message = new Message();
				message.setMessageParentId(0);
				message.setMessageOpen(0);
				message.setMessageState(0);
				message.setMessageTitle(messageTitle);
				message.setMessageIsmore(0);
				message.setMessageBody(model);
				message.setMessageType(1);//0为私信、1为系统消息、2为留言
				message.setFromMemberId(sellerVo.getMemberId());
				message.setFromMemberName("system");
				message.setToMemberId(member.getMemberId().toString());
				message.setToMemberName(member.getMemberName());
				message.setMessageTime(DateUtil.unixTimeStampInt().intValue());
				message.setMessageClass(memberMsgTpl.getMmtClass());
				messages.add(message);
			}
			messageMapper.batchInsert(messages);
		}else{

			for(Member member:members){


				Message message = new Message();
				message.setMessageParentId(0);
				message.setMessageOpen(0);
				message.setMessageState(0);
				message.setMessageTitle(messageTitle);
				message.setMessageIsmore(0);
				message.setMessageBody(messageBody);
				message.setMessageType(1);//0为私信、1为系统消息、2为留言
				message.setFromMemberId(sellerVo.getMemberId());
				message.setFromMemberName("system");
				message.setToMemberId(member.getMemberId().toString());
				message.setToMemberName(member.getMemberName());
				message.setMessageTime(DateUtil.unixTimeStampInt().intValue());
				message.setMessageClass(0);
				messages.add(message);

			}
			messageMapper.batchInsert(messages);


		}





	}

	@Override
	public List<Message> selectByCondition(Message message) {
		return messageMapper.selectByCondition(message);
	}
}
